<template>
	<view class="user-info">
		<view class="content">
			<head-image :name="userInfo.name" :url="userInfo.headImage" :size="160"
				@click="selectHeadImage"></head-image>
			<view class="info-item">
				<text>{{userInfo.name}}</text>
			</view>
		</view>
		<!-- <text class='head-text' v-if="userInfo.headImage==''">请点击圆圈添加人物头像</text> -->
		<view class="line"></view>

		<view class="tabContent" v-show="true">
			<view class="paramBox">
				<view class="param-title">个人信息</view>
				<view class="param-item">
					<label>姓名</label>
					<uni-easyinput prefixIcon="heart" :inputBorder='false' v-model="userInfo.name"
						:placeholderStyle="placeholderStyle" placeholder='请输入姓名'>
					</uni-easyinput>
				</view>
				<view class="param-item">
					<label>性别</label>
					<uni-data-select v-model="userInfo.gender" :localdata="genderOption" @change="handleGenderChange"
						label="性别选择">
					</uni-data-select>
				</view>
				<view class="param-item">
					<label>生日</label>
					<picker mode="date" :value="userInfo.birthday" @change="handleDateChange" class="picker">
						<text class="text" v-if="userInfo.birthday!=''">{{userInfo.birthday}}</text>
						<text class="text" v-else>请点击选择出生日期</text>
					</picker>
				</view>
				<view class="param-item">
					<label>籍贯</label>
					<view class="picker2">
						<uni-data-picker :placeholder="userInfo.city" popup-title="请选择城市" collection="opendb-city-china"
							field="code as value, name as text" orderby="value asc" :step-searh="true" self-field="code"
							parent-field="parent_code" @change="handleCityChange" :maxLevel="2">
						</uni-data-picker>
					</view>
				</view>
				<view>
					<view v-for="(relative, relativeIndex) in userInfo.relative" :key="relativeIndex">
						<view class="param-item">
							<label>联系人{{relativeIndex + 1}}</label>
							<button class="label-button" @click="addRelative(relative.name, relative.phone)"
								v-if="relativeIndex == 0">+</button>
							<uni-easyinput prefixIcon="person" :inputBorder='true' v-model="relative.name"
								:placeholderStyle="placeholderStyle" placeholder='请输入称谓'
								@input="handleRelativeNameChange($event, relativeIndex)">
							</uni-easyinput>
						</view>
						<view class="param-item">
							<label>手机号码{{relativeIndex + 1}}</label>
							<button class="label-button" @click="delRelative" v-if="relativeIndex == 0">-</button>
							<uni-easyinput prefixIcon="person" :inputBorder='true' v-model="relative.phone"
								:placeholderStyle="placeholderStyle" placeholder='请输入手机号码'
								@input="handleRelativePhoneChange($event, relativeIndex)">
							</uni-easyinput>
						</view>
					</view>
				</view>
				<view class="param-title">学校信息</view>
				<view class="param-item">
					<label>年级</label>
					<button @click="openGradeTermPopup" class='button-grade' plain="true"
						v-if="userInfo.grade!=''">{{ userInfo.grade }}</button>
					<button @click="openGradeTermPopup" class='button-grade' plain="true" v-else>请点击选择年级</button>
				</view>
				<vk-data-goods-sku-popup ref="skuPopup" v-model="gradeTermPopupData.show" border-radius="20"
					:z-index="990" :localdata="gradeGoodsInfo" :default-select="defaultSku" :selected-init="true"
					:mode="gradeTermPopupData.mode" :theme="gradeTermPopupData.theme"
					:show-close="gradeTermPopupData.showClose" :hide-stock="gradeTermPopupData.hideStock"
					:mask-close-able="gradeTermPopupData.maskCloseAble" @open="onOpenGradeTermPopup"
					@close="onCloseGradeTermPopup" @add-cart="confirmGradeTermSelection"></vk-data-goods-sku-popup>
				<view class="param-item">
					<label>班级</label>
					<uni-easyinput prefixIcon="heart" :inputBorder='false' v-model="userInfo.class"
						:placeholderStyle="placeholderStyle" placeholder='请输入, 例如:1'>
					</uni-easyinput>
				</view>
				<view class="param-item">
					<label>备注</label>
					<uni-easyinput prefixIcon="edit" :inputBorder='false' v-model="userInfo.notes"
						:placeholderStyle="placeholderStyle" placeholder='请输入备注信息'>
					</uni-easyinput>
				</view>
			</view>
			<!-- 隔离与按钮直接的间隔 -->
			<view style="height: 30rpx;"></view>
			<view>
				<button class="button" type="primary" @tap="addUser">添 加 用 户</button>
			</view>

		</view>
	</view>
</template>

<script>
	import {
		reactive,
		toRefs,
		computed,
		watch
	} from 'vue';

	import {
		onShow,
		onLoad
	} from '@dcloudio/uni-app';
	import {
		city_list
	} from '@/utils/city_list.js';

	import vkDataGoodsSkuPopup from '@/components/vk-data-goods-sku-popup/vk-data-goods-sku-popup.vue';
	import uniDataSelect from '@/uni_modules/uni-data-select/components/uni-data-select/uni-data-select.vue';
	import UniDataPicker from '@/uni_modules/uni-data-picker/components/uni-data-picker/uni-data-picker.vue';
	import {
		gender_options,
		default_stage_grade
	} from '@/utils/enum.js'

	export default {
		components: {
			UniDataPicker
		},
		setup() {
			const db_student = uniCloud.importObject("db_student");
			const genderOption = gender_options;
			const cityList = city_list;
			const placeholderStyle = "color:#000000;font-size:14px;font-weight:546;";
			const gradeList = default_stage_grade;

			// 使用reactive创建响应式数据对象userInfo
			const state = reactive({
				userInfo: {
					name: '',
					headImage: '',
					gender: '',
					birthday: '',
					city: '',
					relative: [{
						name: '',
						phone: ''
					}],
					grade: '',
					class: '',
					notes: ''
				},
				gradeGoodsInfo: {},
				defaultSku: {
					sku: ["小学", "一年级", "上学期"]
				},
				gradeTermPopupData: {
					show: false,
					goods_id: "001",
					theme: "default",
					showClose: true,
					maskCloseAble: true,
				}
			});

			// 处理选择图片的点击事件，仅更新组件内userInfo的headImage数据，暂不涉及与studentStore交互（新增用户时先收集数据）
			const selectHeadImage = () => {
				uni.chooseImage({
					count: 1, // 只允许选择一张图片
					sourceType: ['album', 'camera'], // 可以从相册或相机选择图片
					success: (res) => {
						console.log('res', res)
						state.userInfo.headImage = res.tempFilePaths[0];
					},
					fail: (err) => {
						uni.showToast({
							title: '选择图片失败，请检查权限或稍后再试',
							icon: 'none'
						});
						console.log('选择图片失败：', err);
					}
				});
			};

			// 处理选择变化的方法，仅更新组件内userInfo的gender数据，暂不涉及与studentStore交互（新增用户时先收集数据）
			const handleGenderChange = (e) => {
				state.userInfo.gender = e;
			};

			const handleDateChange = (e) => {
				state.userInfo.birthday = e.detail.value;
			};

			// 处理选择籍贯城市变化，仅更新组件内userInfo的ancestral_home数据，暂不涉及与studentStore交互（新增用户时先收集数据）
			const handleCityChange = (e) => {
				state.userInfo.city = e.detail.value;
			};

			// 添加输入合法性验证（以手机号码验证为例）到handleRelativePhoneChange函数，仅更新组件内对应联系人的手机号码信息，暂不涉及与studentStore交互（新增用户时先收集数据）
			const handleRelativePhoneChange = (e, relativeIndex) => {
				const newRelativePhone = e;
				state.userInfo.relative[relativeIndex].phone = newRelativePhone;
			};

			const handleRelativeNameChange = (e, relativeIndex) => {
				// 获取当前输入的新称谓
				const newRelativeName = e;
				state.userInfo.relative[relativeIndex].name = newRelativeName;
			};

			// 打开年级学期选择弹窗，根据数据获取结果决定是否打开
			const openGradeTermPopup = () => {
				state.gradeGoodsInfo = getGradeTermGoodsInfo(state.gradeTermPopupData.goods_id);
				if (!state.gradeGoodsInfo) {
					return; // 直接返回，不打开弹窗
				}
				state.gradeTermPopupData.show = true;
			};

			// 获取年级学期商品信息，添加提示给用户
			const getGradeTermGoodsInfo = (goodsId) => {
				// 查找gradeList的第几个数组，根据goodsId匹配
				const result = gradeList.find((item) => item._id === goodsId) || null;
				if (!result) {
					uni.showToast({
						title: '年级学期商品信息获取失败，请稍后再试',
						icon: 'none'
					});
				}
				return result;
			};

			// 年级学期选择弹窗打开时的监听方法
			const onOpenGradeTermPopup = () => {
				console.log("监听 - 打开年级学期选择组件");
				if (state.gradeTermPopupData.defaultSku && state.gradeTermPopupData.defaultSku.sku) {
					state.$refs.gradeTermPopup.selectSku(state.gradeTermPopupData.defaultSku);
				}
			};

			// 年级学期选择弹窗关闭时的监听方法
			const onCloseGradeTermPopup = () => {
				console.log("监听 - 关闭年级学期选择组件");
			};

			// 年级学期选择确认后的逻辑处理，仅更新组件内userInfo的相关年级、学期等信息
			const confirmGradeTermSelection = async (selectShop) => {
				console.log("监听 - 年级学期确认选择", selectShop);
				if (selectShop) {
					state.userInfo.grade = selectShop.goods_name
				}
				setTimeout(() => {
					state.gradeTermPopupData.show = false;
				}, 300);
			};

			// 添加联系人的方法，仅更新组件内userInfo的联系人列表信息，
			const addRelative = (name, phone) => {
				if (name && phone) {
					// 直接使用传入的name和phone，而不是空字符串
					state.userInfo.relative.push({
						name,
						phone
					});
				} else {
					uni.showToast({
						title: '姓名和手机号码都不能为空',
						icon: 'none'
					});
				}
			};
			// 删除联系人的方法，仅更新组件内userInfo的联系人列表信息
			const delRelative = () => {
				const lastIndex = state.userInfo.relative.length - 1;
				if (lastIndex > 0) {
					state.userInfo.relative.splice(lastIndex, 1);
					uni.showToast({
						title: '已删除最后一个联系人',
						icon: 'success'
					});
				} else {
					console.log('联系人列表为空，无可删除的联系人');
				}
			};

			const addUser = async () => {
				// 检查必填字段是否有值
				if (!state.userInfo.name) {
					uni.showToast({
						title: '请填写姓名后再添加用户',
						icon: 'none'
					});
					return;
				}

				const studentData = {
					...state.userInfo
				};

				try {
					await db_student.addStudentInfo(studentData);
					uni.showToast({
						title: '学生信息添加成功',
						icon: 'success'
					});
				} catch (error) {
					uni.showToast({
						title: '学生信息添加失败，请重试',
						icon: 'none'
					});
					console.error('添加学生信息出错:', error);
				}
			};


			return {
				...toRefs(state),
				cityList,
				genderOption,
				gradeList,
				placeholderStyle,
				selectHeadImage,
				handleGenderChange,
				handleDateChange,
				handleCityChange,
				handleRelativeNameChange,
				handleRelativePhoneChange,
				addRelative,
				delRelative,
				addUser,
				openGradeTermPopup,
				onOpenGradeTermPopup,
				onCloseGradeTermPopup,
				confirmGradeTermSelection,
			};
		}
	};
</script>

<style lang="scss" scoped>
	.user-info {
		.content {
			height: 100%;
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 20rpx;

			.info-item {
				display: flex;
				align-items: flex-start;
				flex-direction: column;
				padding-left: 40rpx;
				flex: 1;
				font-size: 70rpx;
				font-weight: 600;
				margin: 0rpx 50rpx;
			}
		}

		.head-text {
			padding-left: 30rpx;
			font-size: 20rpx;
			font-weight: 700;
		}

		.line {
			margin: 10rpx;
			border-bottom: 1px solid #aaaaaa;
		}

		.tabContent {
			background: #fff;
			overflow: hidden;
		}

		.param-title {
			background: #f5f5f5;
			height: 80rpx;
			line-height: 80rpx;
			margin: 10rpx 30rpx 0;
			font-size: 28rpx;
			text-indent: 30rpx;
		}

		.param-item {
			height: 80rpx;
			line-height: 80rpx;
			font-size: 26rpx;
			border-bottom: 1rpx solid #f5f5f5;
			margin: 0 30rpx;
			border-left: 1rpx solid #f5f5f5;
			border-right: 1rpx solid #f5f5f5;
			padding: 0 30rpx;
			display: flex;
		}

		.param-item label {
			width: 260rpx;
			color: #999;
		}

		.label-button {
			width: 30rpx;
			display: flex;
			justify-content: center;

		}

		.button-grade {
			width: 85%;
			font-size: 26rpx;
			// font-weight: 550;
			border-style: hidden;
			margin-right: 60rpx;
		}

		.text {
			font-size: 26rpx;
			// font-weight: 500;
		}

		.button {
			align-items: center;
			justify-content: center;
			height: 80rpx;
			line-height: 80rpx;
			font-size: 28rpx;
			width: 90%;
		}

		.picker {
			width: 100%;
			/* 设置宽度为整行宽度 */
			height: 80rpx;
			/* 可根据实际情况调整高度，保持和其他 param-item 一致 */
			line-height: 80rpx;
			font-size: 24rpx;
			display: flex;
			justify-content: flex-start;
			/* 将文本和展开图标两端对齐 */
			align-items: center;
			/* 垂直居中 */
			position: relative;
			/* 为了设置伪元素的定位 */
			padding-left: 110rpx;
		}

		.picker::after {
			content: "";
			position: absolute;
			right: 15rpx;
			/* 根据需要调整右侧距离，设置展开图标的位置 */
			top: 40%;
			width: 15rpx;
			height: 15rpx;
			border-top: 2rpx solid #999;
			border-right: 2rpx solid #999;
			transform: rotate(45deg);
		}

		.picker2 {
			width: 100%;
			/* 设置宽度为整行宽度 */
			height: 80rpx;
			/* 可根据实际情况调整高度，保持和其他 param-item 一致 */
			line-height: 80rpx;
			font-size: 24rpx;
			display: flex;
			justify-content: flex-start;
			/* 将文本和展开图标两端对齐 */
			align-items: center;
			/* 垂直居中 */
			position: relative;
			/* 为了设置伪元素的定位 */
			padding-left: 110rpx;
		}

		.input-border {
			border: #b3e5fc;
			border-radius: 5px;
			padding: 2px 4px;
		}

		.input-selected {
			/* #ifndef APP-NVUE */
			display: flex;
			/* #endif */
			flex-direction: row;
			line-height: 2;
		}

		.data-pickerview {
			height: 300px;
			border: 1px solid #e5e5e5;
			border-radius: 5px;
			/* #ifndef APP-NVUE */
			overflow: hidden;
			/* #endif */
		}
	}
</style>